package com.kancy.framework.job.starter.autoconfigure;

import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.kancy.framework.job.starter.parser.JobConfigParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.env.Environment;

/**
 * 任务自动配置
 *
 * @author kancy
 */
@Configuration
@EnableConfigurationProperties(ZookeeperProperties.class)
@RequiredArgsConstructor
@Slf4j
@ConditionalOnProperty(value = "elastic.job.zk.enabled")
public class ElasticJobAutoConfiguration {

    private final ZookeeperProperties zookeeperProperties;

    /**
     * 初始化Zookeeper注册中心
     */
    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter zookeeperRegistryCenter() {
        ZookeeperConfiguration zkConfig = new ZookeeperConfiguration(zookeeperProperties.getServerLists(),
                zookeeperProperties.getNamespace());
        zkConfig.setBaseSleepTimeMilliseconds(zookeeperProperties.getBaseSleepTimeMilliseconds());
        zkConfig.setConnectionTimeoutMilliseconds(zookeeperProperties.getConnectionTimeoutMilliseconds());
        zkConfig.setDigest(zookeeperProperties.getDigest());
        zkConfig.setMaxRetries(zookeeperProperties.getMaxRetries());
        zkConfig.setMaxSleepTimeMilliseconds(zookeeperProperties.getMaxSleepTimeMilliseconds());
        zkConfig.setSessionTimeoutMilliseconds(zookeeperProperties.getSessionTimeoutMilliseconds());
        return new ZookeeperRegistryCenter(zkConfig);
    }

    @Bean(initMethod = "init")
    @DependsOn("zookeeperRegistryCenter")
    public JobConfigParser jobConfigParser(ApplicationContext ctx, Environment env) {
        return JobConfigParser.builder()
                .applicationContext(ctx)
                .environment(env)
                .zookeeperRegistryCenter(zookeeperRegistryCenter())
                .build();
    }

}
